//
//  FZCookieManager.m
//  FZHybrid
//
//  Created by zzc483 on 2019/1/29.
//  Copyright © 2019年 qiufeng. All rights reserved.
//

#import "FZCookieManager.h"
#import <WebKit/WebKit.h>
#import "FZWKWebViewController.h"
#import "NSDictionary+JSONString.h"

@implementation FZCookieManager

- (void)setCookie:(NSString *)name value:(id)value
{
    FZWKWebViewController *viewController = (FZWKWebViewController *)self.webViewController;
    WKWebView *webView = (WKWebView *)viewController.webView;
    NSURL *originURL = webView.URL;
    NSString *domain = originURL.host;
    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    [cookieProperties setObject:name forKey:NSHTTPCookieName];
    // 手动设置cookie的属性
    [cookieProperties setObject:value forKey:NSHTTPCookieValue];
    if (!domain) {
        [cookieProperties setObject:@"m.tantu.com" forKey:NSHTTPCookieDomain];
    } else {
        [cookieProperties setObject:webView.URL.absoluteString ?: @"" forKey:NSHTTPCookieOriginURL];
    }
    [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
    [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    NSMutableArray *localCookies = [NSKeyedUnarchiver unarchiveObjectWithFile:[self cookieLocalPath]];
    if (localCookies == nil) {
        localCookies = [NSMutableArray arrayWithCapacity:0];
    }
    for (NSHTTPCookie *tempCookie in localCookies) {
        if ([tempCookie.name isEqualToString:cookie.name] && [tempCookie.domain isEqualToString:cookie.domain]) {
            [localCookies removeObject:tempCookie];
            break;
        }
    }
    [localCookies addObject:cookie];
    if ([NSKeyedArchiver archiveRootObject:localCookies toFile:[self cookieLocalPath]]) {
        NSLog(@"save cookie successfully");
    }
    
    NSLog(@"setCookie: %@", [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies);
}

- (void)getCookie:(NSString *)name completion:(void (^)(id))completion
{
    NSMutableDictionary *cookiesDic = [NSMutableDictionary dictionaryWithCapacity:0];
    NSMutableArray *localCookies = [NSKeyedUnarchiver unarchiveObjectWithFile:[self cookieLocalPath]];
    if (localCookies == nil) {
        localCookies = [NSMutableArray arrayWithCapacity:0];
    }
    [localCookies addObjectsFromArray:[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies];
    for (NSHTTPCookie *cookie in localCookies) {
        NSMutableDictionary *cookieProperty = [NSMutableDictionary dictionaryWithDictionary:cookie.properties];
        if (cookieProperty && cookie.expiresDate) {
            cookieProperty[NSHTTPCookieExpires] = cookie.expiresDate.description;
        }
        if (name.length) {
            if ([cookie.name isEqualToString:name]) {
                [cookiesDic addEntriesFromDictionary:cookieProperty];
                break;
            }
        } else {
            [cookiesDic addEntriesFromDictionary:cookieProperty];
        }
    }
    
    if (completion) {
        completion(cookiesDic);
    }
}

- (void)syncCookies:(id)cookies completion:(void (^)(id))completion
{
    if ([cookies isKindOfClass:[NSDictionary class]]) {
        FZWKWebViewController *viewController = (FZWKWebViewController *)self.webViewController;
        WKWebView *webView = (WKWebView *)viewController.webView;
        NSURL *originURL = webView.URL;
        NSString *domain = originURL.host;
        NSMutableArray *localCookies = [NSKeyedUnarchiver unarchiveObjectWithFile:[self cookieLocalPath]];
        if (localCookies == nil) {
            localCookies = [NSMutableArray arrayWithCapacity:0];
        }
        [localCookies filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"expiresDate < %@", [NSDate date]]];
        for (id key in cookies) {
            id value = cookies[key];
            if ([value isKindOfClass:[NSDictionary class]]) {
                value = [value JSONString];
            }
            NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
            [cookieProperties setObject:key forKey:NSHTTPCookieName];
            // 手动设置cookie的属性
            [cookieProperties setObject:value forKey:NSHTTPCookieValue];
            if (!domain) {
                [cookieProperties setObject:@"m.tantu.com" forKey:NSHTTPCookieDomain];
            } else {
                [cookieProperties setObject:webView.URL.absoluteString ?: @"" forKey:NSHTTPCookieOriginURL];
            }
            [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
            [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
            NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
            if (cookie) {
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
                [localCookies addObject:cookie];
            }
    
        }
        if ([NSKeyedArchiver archiveRootObject:localCookies toFile:[self cookieLocalPath]]) {
            NSLog(@"save cookie successfully");
        }
        NSLog(@"syncCookies: %@", [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies);
        NSMutableDictionary *cookiesInfo = [NSMutableDictionary dictionaryWithCapacity:0];
        for (NSHTTPCookie *cookie in localCookies) {
            cookiesInfo[cookie.name] = cookie.value;
        }
        if (completion) {
            completion(cookiesInfo);
        }
    }
}

- (void)removeCookie:(NSString *)name
{
    
}

- (NSString *)cookieLocalPath
{
    NSString *documentPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *cookieDirPath = [documentPath stringByAppendingPathComponent:@"FZCookies"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:cookieDirPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:cookieDirPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [cookieDirPath stringByAppendingPathComponent:@"fzcookies.plist"];
}


@end
